package com.gupao.edu.bio;

import com.gupao.edu.utils.CloseUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description：服务端处理器
 * @author：huabin.lin@sfwl.com.cn
 * @version：2018年11月01日 15:19
 */
public class BioServerHandler implements Runnable {

    private Socket socket;

    public BioServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            String expression;
            int result;
            while (true) {
                // 通过BufferedReader读取一行
                // 如果已经读到输入流尾部，返回null,退出循环
                // 如果得到非空值，就尝试计算结果并返回
                if (null == (expression = in.readLine())) {
                    break;
                }
                System.out.println("服务端收到信息：" + expression);

                result = Calculator.cal(expression);
                out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("服务端发生错误了：" + e.getLocalizedMessage());
        } finally {
            CloseUtil.clearResources(in, out, socket);
        }
    }
}
